package com.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dto.AllTicketsDTO;
import com.dto.IssueDTO;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class JiraServiceFromTxt {
	@Autowired
	DatabaseService databaseService;

	/**
	 * Filling database with all tickets(may take a long time)
	 * 
	 * @throws IOException
	 */
	public void fillDatabaseAllTickets() {

		AllTicketsDTO allTickets;
		String json = null;
		try {
			BufferedReader br = new BufferedReader(new FileReader(new File(JiraServiceFromTxt.class.getClassLoader()
					.getResource("JSONFolder//MyJsonTickets").getPath())));
			StringBuilder sb = new StringBuilder();
			String line = br.readLine();

			while (line != null) {
				sb.append(line);
				// sb.append(System.lineSeparator());
				line = br.readLine();
			}
			json = sb.toString();
			br.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println(json);
		try {
			allTickets = mapJsonToDto(json, AllTicketsDTO.class);
			IssueDTO[] issues = allTickets.getIssues();

			for (IssueDTO issue : issues) {
				// issue.setWatchers(getDTOWatchers(issue.getKey()));

				databaseService.issueIntoEntity(issue);
			}
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * maps json into DTO representation
	 * 
	 * @param json
	 *            as String
	 * @param clazz
	 *            value of Class.class
	 * @return DTO of type Class.class
	 */
	public <T> T mapJsonToDto(String json, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		T object = mapper.readValue(json, clazz);
		return object;
	}

	/**
	 * Returns watchers from Jira using rest api for single ticket
	 * 
	 * @param ticketId
	 *            or key of the ticket
	 * @return WatchersDTO
	 */

	/*
	 * public WatchersDTO getDTOWatchers(String ticketId) throws
	 * JsonParseException, JsonMappingException, IOException { String uri =
	 * jiraUrl + "/rest/api/latest/issue/" + ticketId + "/watchers"; Client
	 * client = Client.create(); client.addFilter(authFilter); WebResource
	 * service = client.resource(uri); String jsonWatchers =
	 * service.get(String.class); WatchersDTO watchers =
	 * mapJsonToDto(jsonWatchers, WatchersDTO.class); return watchers; }
	 */

}
